<?php
/**
 * 这是一个关于PHP JSON编解码函数的示例
 * User: ford
 * Date: 15-7-11
 * Time: 下午9:41
 */
//下面演示PHP中的各种数组类型用JSON函数编解码后的结果
$php_data_types = array(4.1, 3, null, true, false, "hello", new StdClass(), array());


$json = json_encode($php_data_types);
echo "<p>PHP数组变量定义：array(4.1, 3, null, true, false, \"hello\", new StdClass(), array());</p>";
echo "<p>JSON 编码后的结果:</p>\n";
echo "<pre>\n";
var_dump($json);
echo "</pre>";
echo "注意此处将数组的表示方式，外围使用的是方括号。编码为String格式，里面的对象和数组变量的不同表示";

$encoded = json_decode($json);
echo "<p>PHP JSON解码后的结果：</p>\n";
echo "<pre>\n";
var_dump($encoded);
echo "</pre>";

echo "<p>JSON忽略数组的数值下标（即数值下标不会保存在JSON中），但是只要数组里面有一个带有下标的数组元素，那么所有的数组下标都会存储在JSON中，没有的以数字代替。</p>";
echo "<p>下面是嵌套数组变量的定义和编解码：</p>";
$books = array(
	"sample_book" =>	//注释掉这行可发现关联数组和数值下标的不同应用
	array(
			"author"	=> "Lewis Carroll",
			"title"		=> "Alice's Adventures in Wonderland",
			"year"		=> 1865
	),
	array(
			"author"	=> "Yann Martel",
			"title"		=> "Life of Pi",
			"year"		=> 2001
	),
	array(
			"author"	=> "Junot Diaz",
			"title"		=> "The brief Wondrous Life of Oscar Wao",
			"year"		=> 2007
	),
	array(
			"author"	=> "Joseph Heller",
			"title"		=> "Catch-22",
			"year"		=> 1961
	),
	array(
			"author"	=> "Timothy Findley",
			"title"		=> "Pilgrim",
			"year"		=> 1999
	),
	array(
			"author"	=> "Fyodor Dostoyvsky",
			"title"		=> "Brothers Karamazov",
			"year"		=> 1880

	)
);

$json_books = json_encode($books);

echo "<pre>";
var_dump($json_books);
$decoded_books = json_decode($json_books);
var_dump($decoded_books);
echo "</pre>";